import time
import logging

import requests

from conf import config
from helper.meituan.sign_helper import SignHelper
from helper.meituan.request_constant import RequestConstant

logger = logging.getLogger("wechat.helper.meituan")


class QueryShopArea(object):
    """
    查询门店配送范围
    """
    def __init__(self, shop_id, service_code=4011):
        self.delivery_service_code = service_code
        self.shop_id = str(shop_id)
        self.appkey = config.MEITUAN_APP_KEY
        self.secret = config.MEITUAN_APP_SECRET

    def query_shop_area(self):
        secret = self.secret
        data = self.shop_area_request_data()
        sign = SignHelper.get_sign(data, secret)
        logger.info(f"sign={sign}")
        data["sign"] = sign
        url = RequestConstant.QUERY_SHOP_AREA
        try:
            response = requests.post(url, data=data, timeout=30)
            response = response.json()
            logger.info(f"response={response}")
            return response
        except Exception as e:
            logger.error(e)
            return False

    def shop_area_request_data(self):
        data = dict(
            timestamp=int(time.time()),
            version="1.0",
            appkey=self.appkey,
            shop_id=self.shop_id,
            delivery_service_code=self.delivery_service_code,
        )
        return data


if __name__ == '__main__':
    shop_id = "test_0001"
    o = QueryShopArea(shop_id)
    result = o.query_shop_area()
    print(f"result={result}")